package lc.animation;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import com.jme.math.Quaternion;
import com.jme.math.Vector3f;

public class Keyframe implements Externalizable {

	public Vector3f translation;
	public Quaternion rotation;
	public Vector3f scale;

	public Keyframe() {
	}

	public Keyframe(Vector3f translation, Quaternion rotation, Vector3f scale) {
		this.translation = translation;
		this.rotation = rotation;
		this.scale = scale;
	}

	public boolean equals(Object b) {
		if (!(b instanceof Keyframe))
			return false;
		Keyframe k = (Keyframe)b;
		if ((k.translation == null) != (translation == null))
			return false;
		if ((k.rotation == null) != (rotation == null))
			return false;
		if ((k.scale == null) != (scale == null))
			return false;
		return (translation == null || translation.equals(k.translation))
			&& (rotation == null || rotation.equals(k.rotation))
			&& (scale == null || scale.equals(k.scale));
	}

	public int hashCode() {
		return (((translation == null) ? 0 : translation.hashCode()) << 1)
			^ (((rotation == null) ? 0 : rotation.hashCode()) << 0)
			^ (((scale == null) ? 0 : scale.hashCode()) << 2);
	}

	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		int version = in.readInt();
		if (version != VERSION)
			throw new IOException("Bad version found in Keyframe.readExternal()");
		byte b;
		float x, y, z, w;
		b = in.readByte();
		if ((b & 1) != 0) {
			x = in.readFloat(); y = in.readFloat(); z = in.readFloat();
			translation = new Vector3f(x, y, z);
		}
		if ((b & 2) != 0) {
			x = in.readFloat(); y = in.readFloat(); z = in.readFloat(); w = in.readFloat();
			rotation = new Quaternion(x, y, z, w);
		}
		if ((b & 4) != 0) {
			x = in.readFloat(); y = in.readFloat(); z = in.readFloat();
			scale = new Vector3f(x, y, z);
		}
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeInt(VERSION);
		byte b = 0;
		if (translation != null)
			b |= 1;
		if (rotation != null)
			b |= 2;
		if (scale != null)
			b |= 4;
		out.writeByte(b);
		if (translation != null) {
			out.writeFloat(translation.x);
			out.writeFloat(translation.y);
			out.writeFloat(translation.z);
		}
		if (rotation != null) {
			out.writeFloat(rotation.x);
			out.writeFloat(rotation.y);
			out.writeFloat(rotation.z);
			out.writeFloat(rotation.w);
		}
		if (scale != null) {
			out.writeFloat(scale.x);
			out.writeFloat(scale.y);
			out.writeFloat(scale.z);
		}
	}

	private final static int VERSION = 2;
}
